const express = require('express')
const User = require('./models/user')
const md5 = require('blueimp-md5')
const salt = require('./config').salt
const multer = require('multer')
const path = require('path')
const fs = require('fs')
const uuidv4 = require('uuid/v4')

//日期
function formatDate (obj){
    // let year = obj.getFullYear()
    // let month = obj.getMonth()+1 > 10? obj.getMonth()+1:'0' + (obj.getMonth()+1)
    // let date = obj.getDate() > 10? obj.getDate() : '0'+ obj.getDate()
    return obj.toISOString().substr(0, 8)
    //return `${year}-${month}-${date}`
}




let storage = multer.diskStorage({
    destination: (req, file, cb) => {
        cb(null, path.join(__dirname, './public/uploads/'))
    },
    filename: (req, file, cb) => {
        let ext = path.extname(file.originalname)
        cb(null, file.fieldname + uuidv4() + ext)
    }

})

const upload = multer({storage:storage})

let router = express.Router()


//首页
router.get('/', (req, res, next) => {
    res.render('index.html', {
        user: req.session.user,

    })
})


//个人主页
router.get('/user/settings/profile', async (req, res)=>{
   
    return res.render('settings/profile.html', {
        user: req.session.user
    })
})



//上传图片
router.post('/upload', upload.single('avatar'), async (req, res)=>{
    //照片路径
    let filePath = '/public/uploads/'+ req.file.filename
    //从数据库 获取照片路径,为删了除做准备
    let oldAvatar = await User.findOne({_id:req.session.user._id})
        oldAvatar = oldAvatar.avatar

    //如果传的不是照片,提示用户
    console.log(req.file)    
    if( !(req.file.mimetype).startsWith('image/')){
        return res.status(200).json({
            err_code: 1,
            message:'请上传照片格式:png,jpeg,gif,jpg'
        })
    } else {
        console.log('aaaa')
            try{
                //数据库存更新照片位置
                let user =  await User.findOneAndUpdate({_id:req.session.user._id},{avatar:filePath},function(err,docs){
                //删掉原来的旧照片
                if(!err){
                    if(path.join(__dirname,oldAvatar) != path.join(__dirname,'/public/img/avatar-default.png')){
                        fs.unlink(path.join(__dirname,oldAvatar), function(err){
                             console.log(err)
                            })
                        }
                    }
                 })
                 //更新session 的照片地址
                 req.session.user.avatar = filePath
        } catch (err) {
            res.status(500).json({
                err_code: 500,
                message:'网站内部服务出现错误,请稍后再试'
            })
        }

        res.status(200).json({
        err_code: 0,
        message:'图片上传成功',
        filePath: filePath
        })
    }
    
})

//更改用户信息
router.post('/change', async (req, res)=>{
    try {
        let user = await User.findOneAndUpdate({_id: req.body._id},{
            nickname:req.body.nickname,
            bio:req.body.bio,
            gender:req.body.gender,
            birthday:req.body.birthday
            }) 

        let newUser = await User.find({_id:req.body._id},{email:1,avatar:1, nickname:1, bio:1, gender:1, birthday:1})
            
    //    newUser[0].birthday = formatDate(newUser[0].birthday) 
       
       req.session.user = newUser[0]
       res.status(200).json({
           err_code: 0,
           message:'基本信息修改成功'
       })
        
    } catch (err) {
        console.log(err)
    }
   

})

//账户设置
router.get('/user/settings/admin', async (req, res)=>{
    return res.render('settings/admin.html', {
        user: req.session.user
    })
})

//更改密码
router.post('/updatepwd', async (req, res)=>{
    let password = md5(md5(req.body.password + salt))
    //原密码错误
    if (!await User.findOne({_id:req.session.user._id, password: password})){
        return res.status(200).json({
            err_code: 1,
            message:'当前密码错误!'
        })
    }
    //两次密码不一致
    if(req.body.newpassword !== req.body.confirm){
        return res.status(200).json({
            err_code: 2,
            message:'新的密码 和 确认密码 不一致'
        })
    }
    //更改密码
        //加密新密码
    let newpassword =  md5(md5(req.body.newpassword + salt)) 
    if( await User.findOneAndUpdate({_id:req.session.user._id},{password:newpassword})){
        return res.status(200).json({
            err_code: 0,
            message:'密码设置成功,请重新登录!'
        })
    } 

})

//删除账号
router.post('/delete', async (req, res)=>{
    try{
        if(await User.findOneAndDelete({_id:req.session.user._id})){
            return res.status(200).json({
                err_code: 0,
                message:'账号注销成功,请重新注册!'
            })
        }else{
            return res.status(200).json({
                err_code: 1,
                message:'注销失败,请重试试!'
            })
        } 
         
   
    } catch (err) {
        console.log(err)
        return res.status(500).json({
            err_code: 2,
            message:'网站内部出现错误,请稍再试!'
        })
    }


})


module.exports = router
